package com.tydic.springboot.util;

import org.apache.poi.hpsf.ClassIDPredefined;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class HttpServletUtil {

    /**
     * @param response 响应结果对象
     * @param fileName 文件名
     * @throws UnsupportedEncodingException 不支持编码异常
     * @设置响应结果
     */
    public static void setResponse(HttpServletRequest request, HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        response.reset();//清空response缓存信息
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        response.setHeader("Access-control-Allow-Origin", "*");

        //设置编码格式
        response.setCharacterEncoding("UTF-8");

        //设置响应类型
        response.setContentType(getContentType(fileName));

        //返回浏览器类型，设置导出文件名称（避免乱码）
        String browser = request.getHeader("User-Agent");
        fileName = URLEncoder.encode(fileName, "UTF-8");
        if (browser.toLowerCase().contains("chrome") || browser.toLowerCase().contains("firefox")) {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        }
        // 设置响应头
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName);
    }

    private static String getContentType(String fileName) {
        ClassIDPredefined[] values = ClassIDPredefined.values();
        for (ClassIDPredefined value : values) {
            String fileExtension = value.getFileExtension();
            if (fileExtension != null && fileName.toLowerCase().endsWith(fileExtension)) {
                return value.getContentType();
            }
        }
        return "application/octet-stream;charset=utf-8";
    }
}
